﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Hangfire;
using KJFrame.Core.Job;
using KJFrame.Core.Job.Config;
using KJFrame.Core.Job.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace KJFrame.Core.HangfireDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(x => x.UseSqlServerStorage("server=192.168.1.109;database=Hangfire;User ID=sa;Password=198603yang;"));
            services.AddSingleton<IRepeatJob, OrderTask>();
            services.Configure<JobConfigs>(Configuration.GetSection("JobConfigs"));
            //services.AddHangfire(x => x.UseRedisStorage("redis 连接地址"));
        }

        /// <summary>
        /// 注册管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            #region 
            // 配置 登陆
            //var filter = new BasicAuthAuthorizationFilter(
            //new BasicAuthAuthorizationFilterOptions
            //{
            //    SslRedirect = false,          // 是否将所有非SSL请求重定向到SSL URL
            //    RequireSsl = false,           // 需要SSL连接才能访问HangFire Dahsboard。强烈建议在使用基本身份验证时使用SSL
            //    LoginCaseSensitive = false,   //登录检查是否区分大小写
            //    Users = new[]
            //    {
            //      new BasicAuthAuthorizationUser
            //       {
            //        Login ="hangfire",//用户名
            //        PasswordClear="111"
            //         // Password as SHA1 hash
            //          //Password=new byte[]{ 0xf3,0xfa，，0xd1 }
            //        }
            //    }
            //});
            //var optionsDashboard = new DashboardOptions
            //{
            //    //Authorization = new[] { new HangfireDashboardAuthorizationFilter() }

            //    //AuthorizationFilters = new[]
            //    //{
            //    //    filter
            //    //}

            //};
            //app.UseHangfireDashboard("/hf", optionsDashboard);//启动hangfire面板 
            #endregion

            //配置作业队列
            var options = new BackgroundJobServerOptions
            {
                Queues = new[] { "a", "default" },// 队列名称，只能为小写
                WorkerCount = Environment.ProcessorCount * 5, //并发任务数
                ServerName = "hangfire1",//服务器名称
                SchedulePollingInterval = TimeSpan.FromSeconds(30),//未设置轮询间隔Hangfire默认是15秒轮询间隔
            };
            app.UseHangfireServer(options);//启动hangfire服务并在数据库中创建表

            app.UseJob(Configuration);

            app.UseHangfireDashboard();//启动hangfire面板

            app.Run(async (context) =>
            {
                //Hangfire作业4种方式：队列、延迟、重复、延续
                #region 队列作业
                //队列(发布/订阅)作业
                //BackgroundJob.Enqueue<EmailService>(x => x.Send(13, "Hello!"));
                #endregion

                #region 延迟作业
                //延迟作业
                //BackgroundJob.Schedule(() => Delayed(), TimeSpan.FromMinutes(1));
                #endregion

                #region 重复作业
                //重复作业
                //RecurringJob.AddOrUpdate(() => DailyJob(), Cron.Daily);
                //RecurringJob.AddOrUpdate(() => DailyJob(), "*/5 * * * * ?");
                #endregion

                #region 延续作业
                //延续作业
               ///* var id = BackgroundJob.Enqueue(() => ContinueWith*/1());
               // BackgroundJob.ContinueWith(id, () => ContinueWith2());
                #endregion
            });            
        }

        /// <summary>
        /// 队列作业
        /// </summary>
        public void FireAndForget()
        {
            //File.AppendAllText("Job\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", "队列作业执行：" + DateTime.Now + System.Environment.NewLine);
        }

        /// <summary>
        /// 延迟作业
        /// </summary>
        public void Delayed()
        {
            //File.AppendAllText("Job\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", "延迟作业执行：" + DateTime.Now + System.Environment.NewLine);
        }

        /// <summary>
        /// 重复作业
        /// </summary>
        public void DailyJob()
        {
            //File.AppendAllText("Job\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", "重复作业执行：" + DateTime.Now + System.Environment.NewLine);
        }

        /// <summary>
        /// 延续作业1
        /// </summary>
        public void ContinueWith1()
        {
            //File.AppendAllText("Job\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", "延续作业1执行：" + DateTime.Now + System.Environment.NewLine);
        }

        /// <summary>
        /// 延续作业2
        /// </summary>
        public void ContinueWith2()
        {
            //File.AppendAllText("Job\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", "延续作业2执行：" + DateTime.Now + System.Environment.NewLine);
        }
    }

    public class EmailService
    {
        public void Send(int num, string msg)
        {
            //File.AppendAllText("Job\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", "方法Send执行，参数值：" + num + msg + "，时间:" + DateTime.Now + System.Environment.NewLine);
        }
    }
}
